package com.york.tinyrpc.example.provider;

import com.york.tinyrpc.example.common.service.UserService;
import com.york.tinyrpc.protoss.TinyRpcApplication;
import com.york.tinyrpc.protoss.config.RegistryCenterConfig;
import com.york.tinyrpc.protoss.config.TinyRpcConfig;
import com.york.tinyrpc.protoss.constant.RegistryCenterTypeConstants;
import com.york.tinyrpc.protoss.constant.TinyRpcConstants;
import com.york.tinyrpc.protoss.model.ServiceMetaInfo;
import com.york.tinyrpc.protoss.registry.LocalRegistry;
import com.york.tinyrpc.protoss.registry.center.RegistryCenter;
import com.york.tinyrpc.protoss.registry.center.RegistryCenterFactory;
import com.york.tinyrpc.protoss.server.HttpServer;
import com.york.tinyrpc.protoss.server.VertxHttpServer;
import com.york.tinyrpc.protoss.server.tcp.VertxTcpServer;

/**
 * 简易服务提供者示例
 */
public class EasyProviderExample {

    public static void main(String[] args) {

        // 初始化TinyRPC的读取配置信息
        TinyRpcApplication.init();

        // 服务提供方启动时顺便注册服务
        LocalRegistry.register(UserService.class.getName(), UserServiceImpl.class);

        // todo proto版本只是注册到了本地的服务注册器上，protoss版本需要注册到服务中心便于服务发现
        // 注册服务到注册中心
        TinyRpcConfig rpcConfig = TinyRpcApplication.getRpcConfig();
        RegistryCenterConfig registryCenterConfig = rpcConfig.getRegistryCenterConfig();
        // 获取注册中心
        RegistryCenter registryCenter = RegistryCenterFactory.getRegistryCenterByType(registryCenterConfig.getRegistryCenterType());
        ServiceMetaInfo serviceMetaInfo = ServiceMetaInfo.builder().serviceName(UserService.class.getName())
                .serviceVersion(TinyRpcConstants.DEFAULT_SYSTEM_VERSION)
                .serviceHost(rpcConfig.getServerHost())
                .servicePort(rpcConfig.getServerPort()).build();
        try {
            registryCenter.serviceRegister(serviceMetaInfo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // protoss版本： 启动基于 TCP 的 web 服务，读取配置文件中的信息从此注册在TinyRPC中
        VertxTcpServer tcpServer = new VertxTcpServer();
        tcpServer.doStart(TinyRpcApplication.getRpcConfig().getServerPort());
    }
}